package com.example.demoapp.bean.util;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;

public class GlideImageGetter implements Html.ImageGetter {
    private Context context;
    private TextView textView;

    public GlideImageGetter(Context context, TextView textView) {
        this.context = context;
        this.textView = textView;
    }

    @Override
    public Drawable getDrawable(String source) {
        final UrlDrawable urlDrawable = new UrlDrawable();
        Glide.with(context)
                .load(source)
                .into(new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                        Drawable drawable = resource;

                        int width = drawable.getIntrinsicWidth();
                        int height = drawable.getIntrinsicHeight();

                        int maxWidth = textView.getWidth(); // 获取 TextView 的宽度
                        if (maxWidth > 0 && width > maxWidth) {
                            float ratio = (float) maxWidth / (float) width; // 计算缩放比例
                            width = maxWidth;
                            height = (int) (height * ratio);
                        }

                        drawable.setBounds(0, 0, width, height); // 设置 Drawable 的边界

                        urlDrawable.setBounds(0, 0, width, height);
                        urlDrawable.setDrawable(drawable);
                        textView.invalidate();
                        textView.setText(textView.getText());
                    }
                });

        return urlDrawable;
    }
}

class UrlDrawable extends Drawable {
    private Drawable drawable;

    @Override
    public void draw(@NonNull Canvas canvas) {
        if (drawable != null) {
            drawable.draw(canvas);
        }
    }

    public void setDrawable(Drawable drawable) {
        this.drawable = drawable;
    }

    @Override
    public void setAlpha(int alpha) { }

    @Override
    public void setColorFilter(@Nullable ColorFilter colorFilter) { }

    @Override
    public int getOpacity() {
        return PixelFormat.TRANSPARENT;
    }
}
